package com.example.video.controller;

import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.example.video.common.Result;
import com.example.video.entity.Device;
import com.example.video.entity.Schedule;
import com.example.video.service.IScheduleService;
import com.example.video.util.laixiOperate.Operate;
import com.example.video.util.scheduled.DynamicTaskScheduler;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URISyntaxException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @since 2024-06-30
 */
@Slf4j
@Controller
@RequestMapping("/schedule")
public class ScheduleController {
    @Resource
    private DynamicTaskScheduler scheduler;
    @Resource
    private IScheduleService scheduleService;
    @Resource
    private Operate laixiOperate;


    @ResponseBody
    @PostMapping("/schedule/upload")
    public Result<String> setSchedule(String hours, String minutes, String role){
        Result<String> rs = new Result<>();
        rs.setCode(0);
        rs.setMsg("成功！");
        log.info("schedule ->/schedule/upload ->msg: "+hours+":"+minutes+" role = "+role);
        Schedule schedule = scheduleService.getItemByRole(role);
        if(schedule == null){
            schedule = new Schedule();
            schedule.setRole(role);
            schedule.setTime(hours+":"+minutes);
            scheduleService.save(schedule);
        }
        String result = scheduler.scheduleTask( schedule.getRole(), ()->{
            log.info("scheduleTask -> 定时任务执行中...");
            List<Device> devices = Db.lambdaQuery(Device.class)
                    .eq(Device::getRole, role)
                    .list();
            if(devices.isEmpty()){
                log.info("admin ->/schedule/upload ->msg: 设备为空！");
            }else {
                List<String> deviceIds = devices.stream()
                        .map(Device::getDeviceId)
                        .collect(Collectors.toList());
                try {
                    log.info("admin ->/schedule/upload ->msg: 结果= "+laixiOperate.excuJs(deviceIds,"request"));
                } catch (URISyntaxException | InterruptedException e) {
                    log.info("admin ->/schedule/upload -> task ->msg: 来喜服务连接失败！"+e.getMessage());
                }
            }

        }, LocalDateTime.now().withHour(Integer.parseInt(hours)).withMinute(Integer.parseInt(minutes)).withSecond(0));

        rs.setData(result);
        return rs;
    }

}
